package com.fj.netty.chat.server.service.impl;

import com.fj.netty.chat.pojo.GroupChat;
import com.fj.netty.chat.server.service.GroupSession;
import com.fj.netty.chat.server.service.ServiceFactory;
import com.fj.netty.chat.server.service.Session;
import io.netty.channel.Channel;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author fj
 * @date 2024/1/12 14:19
 */
public class MapGroupSessionImpl implements GroupSession {
    private final ConcurrentHashMap<String,GroupChat> groupChatMap = new ConcurrentHashMap<>();
    @Override
    public GroupChat create(String username, String groupName, Set<String> members) {
        if (groupChatMap.get(groupName)!=null){
            throw new IllegalArgumentException("组已存在");
        }
        members.add(username);
        GroupChat groupChat = new GroupChat();
        groupChat.setCreator(username);
        groupChat.setName(groupName);
        groupChat.setMemberSet(members);
        groupChatMap.put(groupName, groupChat);
        return groupChat;
    }

    @Override
    public void remove(String username, String groupName) {
        GroupChat groupChat = groupChatMap.get(groupName);
        if (groupChat == null){
            throw new IllegalArgumentException("组不存在");
        }
        if (!groupChat.getCreator().equals(username)){
            throw new IllegalArgumentException("非法操作，非群主");
        }
        groupChatMap.remove(groupName);
    }

    @Override
    public GroupChat join(String username, String groupName) {
        GroupChat groupChat = groupChatMap.get(groupName);
        if (groupChat == null){
            throw new IllegalArgumentException("组不存在");
        }
        groupChat.getMemberSet().add(username);
        return groupChat;
    }

    @Override
    public void quit(String username, String groupName) {
        GroupChat groupChat = groupChatMap.get(groupName);
        if (groupChat == null){
            throw new IllegalArgumentException("组不存在");
        }
        groupChat.getMemberSet().remove(username);
    }

    @Override
    public Set<String> members(String groupName) {
        GroupChat groupChat = groupChatMap.get(groupName);
        if (groupChat == null){
            throw new IllegalArgumentException("组不存在");
        }
        return groupChat.getMemberSet();
    }

    @Override
    public Set<Channel> memberChannels(String groupName) {
        Session session = ServiceFactory.getSession();
        return groupChatMap.get(groupName).getMemberSet().stream().map(session::getChannel).collect(Collectors.toSet());
    }
}
